<?php
namespace Home\Controller;
use Think\Controller;
class LoginController extends Controller {

    //用户登录
    public function index()
    {
        if(IS_POST){
            $where['username'] = I('post.username');
            $info = M('user')->where($where)->find();
            //用户名错误
            if(!$info){
                $this->error('用户名错误',U('home/login/index'),1);
            }
            $password = md5(md5(I('post.password')));
            if($password != $info['password']){
                $this->error('密码错误',U('home/login/index'),1);
            }
            session('id',$info['id']);
            session('username',$info['username']);
            session('truename',$info['truename']);
            session('logintime', $info['logintime']); //上次登录时间
            session('logintime', $info['logintime']); //上次登录IP
            //更新登录时间
            $ip = $_SERVER['REMOTE_ADDR'];
            M('user')->where('id=' . $info['id'])->save(array('logintime' => time(),ip=>$ip));
            //跳转到指定页
            $this->success('登录成功', U('home/console/index'),1);
        }else{
            $this->display();
        }
    }

    //用户退出
    public function loginout()
    {
        session(null);
        $this->redirect('home/index/index');
    }

    //修改密码
    public function forget()
    {
        if(IS_POST){
            $username = I('post.username');
            $phone = I('post.phone');
            $password = I('post.password');
            $user = M('user')->where(['username'=>$username])->find();
            if(!$user){
                $this->error('用户名输入错误',U('home/login/forget'),1);
            }else{ 
                /*if($phone != $user['phone']){
                    $this->error('手机号码输入错误',U('home/login/forget'),1);
                }  */
                $arrs['password'] = md5(md5($password));
                $info = M('user')->where(['id'=>$user['id']])->save($arrs);  
                if($info){
                    $this->success('修改成功',U('home/login/index'),1); 
                }else{
                    $this->error('修改失败',U('home/login/forget'),1); 
                }
            }
        }else{
            $this->display();
        }
    }
}